package com.ruoyi.web.controller.common;

import com.google.code.kaptcha.Producer;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.mobilecode.MsgCodeService;
import com.ruoyi.common.utils.sign.Base64;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 验证码操作处理
 * 
 * @author ruoyi
 */
@RestController
public class CaptchaController
{
    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private MsgCodeService msgCodeService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private ISysConfigService sysConfigService;

    // 验证码类型
    @Value("${ruoyi.captchaType}")
    private String captchaType;

    /**
     * 生成验证码
     */
    @GetMapping("/captchaImage")
    public AjaxResult getCode(HttpServletResponse response) throws IOException
    {
        // 保存验证码信息
        String uuid = IdUtils.simpleUUID();
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;

        String capStr = null, code = null;
        BufferedImage image = null;

        // 生成验证码
        if ("math".equals(captchaType))
        {
            String capText = captchaProducerMath.createText();
            capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            image = captchaProducerMath.createImage(capStr);
        }
        else if ("char".equals(captchaType))
        {
            capStr = code = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        }

        redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try
        {
            ImageIO.write(image, "jpg", os);
        }
        catch (IOException e)
        {
            return AjaxResult.error(e.getMessage());
        }

        AjaxResult ajax = AjaxResult.success();
        ajax.put("uuid", uuid);
        ajax.put("img", Base64.encode(os.toByteArray()));
        return ajax;
    }

    /**
     * 发送短信验证码
     * @param mobile
     * @return
     */
    @GetMapping("/mobilecode")
    public AjaxResult mobilecode(@RequestParam String mobile){

        //判断是否生成过
        String s = redisTemplate.opsForValue().get("wsbregister" + mobile + "phone");
        if(s!=null){
            return AjaxResult.error("十分钟内只能获取一次验证码");
        }


        StringBuffer stringBuffer=new StringBuffer();
        for (int x=0;x<=5;x++) {
            int random = (int) (Math.random() * (10 - 1));
            stringBuffer.append(random);
        }
        String string = stringBuffer.toString();
        Boolean flag = msgCodeService.sendMsg(mobile,string);
        if(!flag){
            return AjaxResult.error("短信发送失败");
        }
        //存redis 10分钟有效期
        redisTemplate.opsForValue().set("wsbregister"+mobile+"phone",string,600, TimeUnit.SECONDS);
        return AjaxResult.success("发送成功");
    }

    /**
     * 验证短信验证码是否正确
     * @param mobile
     * @param code
     * @return
     */
    @GetMapping("/checkcode")
    public AjaxResult checkCode(@RequestParam String mobile,@RequestParam String code){
        //从redis中获取code
        String s = redisTemplate.opsForValue().get("wsbregister" + mobile + "phone");
        if(s==null){
            return AjaxResult.error("验证码错误");
        }
        if(!s.equals(code)){
            return AjaxResult.error("验证码错误");
        }
        //验证码正确则清除redis缓存
        redisTemplate.delete("wsbregister" + mobile + "phone");

        return AjaxResult.success("toSava");
    }

    @GetMapping("/applyrule")
    public AjaxResult applyrule(){
        return AjaxResult.success(this.sysConfigService.findApplyRule());
    }

}
